package com.atguigu.demojuc.chap08;

import java.util.concurrent.*;

/**
 * 自定义线程池：重点7个参数及工作原理
 *
 */
public class CustomizeThreadPoolDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2, //核心线程数
                5, //最大线程数
                0, //等待空闲时间,时间到达会销毁非核心线程数。核心线程不销毁
                TimeUnit.MILLISECONDS, //时间单位
                new ArrayBlockingQueue<>(10), //任务等待队列
                Executors.defaultThreadFactory(), //线程工厂
                //饱和拒绝策略
                //new ThreadPoolExecutor.AbortPolicy()  //直接抛异常 java.util.concurrent.RejectedExecutionException
                //new ThreadPoolExecutor.CallerRunsPolicy() // 交给调用者线程处理
                //new ThreadPoolExecutor.DiscardOldestPolicy() //等待最早的丢弃
                //new ThreadPoolExecutor.DiscardPolicy() //丢弃刚来的任务
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        executor.submit(runnable); //重新将任务提交给线程池处理。
                    }
                }
        );

        //execute()方法只能接收Runnable参数
        //threadPoolExecutor.execute(()->{});

        for (int i = 1; i <= 16; i++) {
            String num = String.valueOf(i);
            //submit()方法可以接收Rnnable或Callable。推荐
            Future<Integer> futureResult = threadPoolExecutor.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in number="+num);
                //Thread.sleep(2000);
                return 100;
            });

            /*try {
                Integer result = futureResult.get();
                System.out.println("result = " + result);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }*/
        }




        //threadPoolExecutor.shutdown(); //关闭线程池。
    }
}
